package org.lds.hotkey.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolUtil {
    public static ExecutorService newExecutor(String threadName, int corePoolSize) {
        return new ThreadPoolExecutor(corePoolSize, corePoolSize, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000),
                new CustomThreadFactory(threadName), new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    static class CustomThreadFactory implements ThreadFactory {
        private final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        public CustomThreadFactory(String threadName) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();

            if (StringUtils.isEmpty(threadName)) {
                threadName = "pool";
            }

            namePrefix = threadName + "-" + poolNumber.getAndIncrement() + "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
